package com.controller;

import com.po.Activity;
import com.po.Msg;
import com.po.User;
import com.service.ActivityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/activity")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @PostMapping("/activities/{id}")
    public String xiangxi(@PathVariable Long id, Model model, HttpSession session) {
        Activity activity = activityService.findById(id);
        int num=activity.getView();
        activity.setView(num+1);
        activityService.saveActivity(activity);
        User user = (User) session.getAttribute("user");
        if (user != null) {
            List<Activity> list = activityService.findActivity(user.getId());
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getId().equals(id)) {
                    System.out.println("已报名");
                    model.addAttribute("tip", "成功");
                }
            }
        } else {
            model.addAttribute("tip", null);
        }
        model.addAttribute("detail", activity);
        System.out.println("111");
        return "/activities";
    }


    //参加活动enroll
    @PostMapping("/enroll/{id}")
    @ResponseBody
    public Msg enroll(@PathVariable Long id, HttpSession session) {
        User u = (User) session.getAttribute("user");
        if (u == null) {
            return Msg.error();
        } else {
            Long u_id = u.getId();
            int i = activityService.save(id, u_id);
            Activity activity=activityService.findById(id);
            activity.setNum(activity.getNum()+1);
            activityService.saveActivity(activity);
            if (i != 0) {
                return Msg.success();
            } else {
                return Msg.fail();
            }
        }
    }

    //取消活动enroll
    @PostMapping("/cancel/{id}")
    @ResponseBody
    public Msg cancel(@PathVariable Long id, HttpSession session,Model model) {
        User u = (User) session.getAttribute("user");
        System.out.println(u);
        System.out.println(u.getId());
        Long u_id = u.getId();
        int i = activityService.delete(id, u_id);
        Activity activity=activityService.findById(id);
        activity.setNum(activity.getNum()-1);
        activityService.saveActivity(activity);
        if (i != 0) {
            model.addAttribute("tip",null);
            return Msg.success();
        } else {
            return Msg.fail();
        }

    }

}
